﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Microsoft.Office.Interop.Excel;

namespace RESP_IIWaterAssessment
{
    public partial class GMSBalanceForm : Form
    {
        public GMSBalanceForm(bool rep)
        {
            isReport = rep;
            InitializeComponent();
        }

        int avpID, regID;
        const string category = "GMSType";
        tb_GMSBalance GMSbalance;

        bool isReport = false;

        private void GMSBalanceForm_Load(object sender, EventArgs e)
        {
            if (isReport)
            {
                buttonAddBalance.Visible = tbCost.Visible = label6.Visible = chbKvartal.Enabled = cbKvartal.Enabled = false;
                buttonPrint.Visible = true;
            }
            else
            {
                buttonExcel.Visible = buttonShowReport.Visible = chbGMS.Visible = chbKvartal.Visible = chbYear.Visible = false;
                buttonPrint.Visible = false;
            }

            cbRegion.SelectedIndexChanged -= cbRegion_SelectedIndexChanged;
            cbRegion.DataSource = UtilClass.FillCBRegions();
            cbRegion.DisplayMember = "Name";
            cbRegion.ValueMember = "ID";

            if (InformationClass.isAdmin)
            {
                cbRegion.SelectedIndex = -1;
                cbRegion.Text = string.Empty;
                cbRegion.SelectedIndexChanged += new EventHandler(cbRegion_SelectedIndexChanged);
            }
            else
            {
                cbRegion.Enabled = false;
                regID = InformationClass.regionID;
                cbRegion.SelectedIndexChanged += new EventHandler(cbRegion_SelectedIndexChanged);
                cbRegion.SelectedValue = regID;
                cbRegion_SelectedIndexChanged(cbRegion, null);
                cbAVP.Enabled = true;
                cbAVP.Text = string.Empty;
                //toolStrip1.Visible = false;
            }

            cbGMS.DataSource = UtilClass.FillCBCategory(category);
            cbGMS.DisplayMember = "Name";
            cbGMS.ValueMember = "ID";

            for (int i = 1991; i < 2100; i++)
            {
                cbYear.Items.Add(i);
            }

            cbYear.SelectedIndex = cbYear.Items.IndexOf(DateTime.Now.Year);
            cbKvartal.SelectedIndex = 0;
        }

        private void cbRegion_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cbRegion.SelectedIndex >= 0)
            {
                cbAVP.Enabled = true;
                regID = Convert.ToInt32(cbRegion.SelectedValue);
                cbAVP.SelectedIndexChanged -= cbAVP_SelectedIndexChanged;
                cbAVP.DataSource = UtilClass.FillAVP(regID);
                cbAVP.ValueMember = "ID";
                cbAVP.DisplayMember = "Name";
                cbAVP.SelectedIndex = -1;
                cbAVP.Text = string.Empty;
                cbAVP.SelectedIndexChanged += new EventHandler(cbAVP_SelectedIndexChanged);
            }
            else
                regID = 0;
        }

        private void cbAVP_SelectedIndexChanged(object sender, EventArgs e)
        {
            int year = Convert.ToInt32(cbYear.Items[cbYear.SelectedIndex]);
            int kvartal = cbKvartal.SelectedIndex + 1;
            DateTime dt = new DateTime();
            switch (kvartal)
            {
                case 1:
                    dt = new DateTime(year, 1, 1);
                    break;
                case 2:
                    dt = new DateTime(year, 4, 1);
                    break;
                case 3:
                    dt = new DateTime(year, 7, 1);
                    break;
                case 4:
                    dt = new DateTime(year, 10, 1);
                    break;
            }

            if (cbAVP.SelectedIndex >= 0)
            {
                avpID = Convert.ToInt32(cbAVP.SelectedValue);
            }
            else
            {
                avpID = 0;
            }

            if (!isReport)
                ShowGMS(regID, avpID, dt);
        }

        private void buttonAddBalance_Click(object sender, EventArgs e)
        {
            if (avpID > 0 && cbGMS.SelectedIndex >= 0)
            {
                int year = Convert.ToInt32(cbYear.Items[cbYear.SelectedIndex]);
                int kvartal = cbKvartal.SelectedIndex + 1;
                int gmsType = Convert.ToInt32(cbGMS.SelectedValue);
                decimal cost;

                DateTime dt = new DateTime();

                switch (kvartal)
                {
                    case 1:
                        dt = new DateTime(year, 1, 1);
                        break;
                    case 2:
                        dt = new DateTime(year, 4, 1);
                        break;
                    case 3:
                        dt = new DateTime(year, 7, 1);
                        break;
                    case 4:
                        dt = new DateTime(year, 10, 1);
                        break;
                }

                if (tbCost.Text.GetDecimalOrDefault(out cost))
                {
                    GMSbalance = DBClass.GMSBalanses
                        .Where(wh => wh.AVPID == avpID && wh.GMSType == gmsType && wh.Date == dt)
                        .SingleOrDefault();

                    if (GMSbalance != null)
                    {
                        GMSbalance.Cost = cost;
                    }
                    else
                    {
                        GMSbalance = new tb_GMSBalance
                        {
                            Date = dt,
                            GMSType = gmsType,
                            AVPID = avpID,
                            Cost = cost
                        };
                        DBClass.GMSBalanses.InsertOnSubmit(GMSbalance);
                    }
                    try
                    {
                        DBClass.RESPContext.SubmitChanges();
                        MessageBox.Show(msgClass.msgSubmitChanges, msgClass.msgAchtung);
                    }
                    catch
                    {
                        MessageBox.Show(msgClass.msgError, msgClass.msgAchtung);
                    }
                    ShowGMS(regID, avpID, dt);
                }
                else
                {
                    if (InformationClass.Lang)
                        MessageBox.Show("Не верно введена стоимость");
                    else
                        MessageBox.Show("Нарҳи нотўғри киритилган");
                    return;
                }
            }
            else
            {
                if (InformationClass.Lang)
                    MessageBox.Show("Не выбрано АВП или тип ГМС");
                else
                    MessageBox.Show("СИУ ёки ГМТ тури танланмаган");
                return;
            }
            tbCost.Text = string.Empty;
        }

        private void ShowGMS(int regID, int avpID, DateTime dt)
        {
            var res = DBClass.GMSBalanses
                .Where(wh => ((wh.AVPID == avpID && avpID > 0) || (wh.AVPID > 0 && avpID == 0)) && wh.Date == dt && UtilClass.GetAll_AVPID_in_regions(regID).Contains(wh.AVPID))
                .Select(se => new
                {
                    GMSType = UtilClass.GetCategoryDisplayName(se.GMSType, category),
                    Cost = se.Cost
                })
                .ToList();
            dgvGMSBalance.DataSource = res;
            if (InformationClass.Lang)
            {
                dgvGMSBalance.Columns["GMSType"].HeaderText = "Тип ГМС";
                dgvGMSBalance.Columns["Cost"].HeaderText = "Стоимость";
            }
            else
            {
                dgvGMSBalance.Columns["GMSType"].HeaderText = "ГМТ тури";
                dgvGMSBalance.Columns["Cost"].HeaderText = "Нарҳи";
            }
        }

        private void buttonShowReport_Click(object sender, EventArgs e)
        {
            int? rID, aID, year, kv, gmsType;

            DateTime? dt;

            if (cbRegion.SelectedIndex >= 0)
                rID = (int)Convert.ToInt32(cbRegion.SelectedValue);
            else
                rID = null;

            if (cbAVP.SelectedIndex >= 0)
                aID = (int)Convert.ToInt32(cbAVP.SelectedValue);
            else
                aID = null;

            if (chbYear.Checked)
                year = (int)Convert.ToInt32(cbYear.Items[cbYear.SelectedIndex].ToString());
            else
                year = null;

            if (chbKvartal.Checked)
            {
                switch (cbKvartal.SelectedIndex)
                {
                    case 0:
                        dt = new DateTime((int)year, 1, 1);
                        break;
                    case 1:
                        dt = new DateTime((int)year, 4, 1);
                        break;
                    case 2:
                        dt = new DateTime((int)year, 7, 1);
                        break;
                    case 3:
                        dt = new DateTime((int)year, 10, 1);
                        break;
                    default:
                        dt = null;
                        break;
                }
            }
            else
                dt = null;

            if (chbGMS.Checked)
                gmsType = (int)Convert.ToInt32(cbGMS.SelectedValue);
            else
                gmsType = null;

            dgvGMSBalance.DataSource = DBClass.RESPContext.GMSBalanceReport(InformationClass.Lang, rID, aID, gmsType, dt, year);

            if (InformationClass.Lang)
            {
                dgvGMSBalance.Columns["AVP"].HeaderText = "АВП";
                dgvGMSBalance.Columns["CatName"].HeaderText = "Тип ГМС";
                dgvGMSBalance.Columns["Cost"].HeaderText = "Стоимость";
            }
            else
            {
                dgvGMSBalance.Columns["AVP"].HeaderText = "СИУ";
                dgvGMSBalance.Columns["CatName"].HeaderText = "ГМТ тури";
                dgvGMSBalance.Columns["Cost"].HeaderText = "Нарҳи";
            }

            dgvGMSBalance.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
            dgvGMSBalance.AutoResizeColumns();
        }

        private void chbYear_CheckedChanged(object sender, EventArgs e)
        {
            cbKvartal.Enabled = chbKvartal.Enabled = chbYear.Checked;
            if (!chbYear.Checked)
            {
                chbKvartal.Checked = false;
            }
        }

        private void dgvGMSBalance_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
        {
            if (isReport && dgvGMSBalance.Columns.Contains("GMSType"))
            {
                if (e.ColumnIndex.Equals(dgvGMSBalance.Columns["GMSType"].Index) && e.Value != null)
                {
                    e.Value = UtilClass.GetCategoryDisplayName((int)e.Value, category);
                }

            }
        }

        Sheets excelsheets;
        Worksheet excelworksheet;
        Microsoft.Office.Interop.Excel.Application excelapp;
        Workbook excelappworkbook;

        private void buttonExcel_Click(object sender, EventArgs e)
        {
            if (dgvGMSBalance.RowCount > 0)
            {
                MessageBox.Show(msgClass.msgWaiting);
                GetReport();
                excelapp.Visible = true;
            }
        }

        private void GetReport()
        {
            excelapp = new Microsoft.Office.Interop.Excel.Application();
            excelapp.SheetsInNewWorkbook = 1;

            if (InformationClass.Lang)
                excelapp.Workbooks.Open(System.Windows.Forms.Application.StartupPath + @"\Templates\i23.xls", false, true, Type.Missing, Type.Missing, Type.Missing, true, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
            else
                excelapp.Workbooks.Open(System.Windows.Forms.Application.StartupPath + @"\Templates\i23uz.xls", false, true, Type.Missing, Type.Missing, Type.Missing, true, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);

            excelappworkbook = excelapp.Workbooks[1];
            excelsheets = excelappworkbook.Worksheets;// .Worksheets[0]; //Sheets 

            int numPage = 1, left = 3, top = 8;

            excelworksheet = (Microsoft.Office.Interop.Excel.Worksheet)excelsheets.get_Item(numPage);

            excelworksheet.Cells.NumberFormat = "@";

            excelworksheet.Cells[4, 3] = cbRegion.Text;

            string str = "Период: ", kvt = InformationClass.Lang ? "Квартал " : "Чорак ";
            if (chbKvartal.Checked)
                str += cbKvartal.Text + kvt;
            if (chbYear.Checked)
                str += cbYear.Text;

            excelworksheet.Cells[6, 2] = str;


            for (int i = 0; i < dgvGMSBalance.Rows.Count; i++)
            {
                for (int j = 0; j < dgvGMSBalance.Columns.Count; j++)
                {
                    excelworksheet.Cells[i + top, dgvGMSBalance.Columns[j].DisplayIndex + left] = dgvGMSBalance[j, i].FormattedValue;
                    addBorder(excelworksheet.Cells[i + top, dgvGMSBalance.Columns[j].DisplayIndex + left]);
                }
                excelworksheet.Cells[i + top, 2] = i + 1;
                addBorder(excelworksheet.Cells[i + top, 2]);
            }
            excelworksheet.Columns.AutoFit();
            excelworksheet.Select(numPage);
        }

        private void addBorder(object p)
        {
            Range tmpRange = excelworksheet.get_Range(p, p);
            tmpRange.Borders[XlBordersIndex.xlEdgeLeft].LineStyle = XlLineStyle.xlContinuous;
            tmpRange.Borders[XlBordersIndex.xlEdgeBottom].LineStyle = XlLineStyle.xlContinuous;
            tmpRange.Borders[XlBordersIndex.xlEdgeRight].LineStyle = XlLineStyle.xlContinuous;
            tmpRange.Borders[XlBordersIndex.xlEdgeTop].LineStyle = XlLineStyle.xlContinuous;
        }

        private void buttonPrint_Click(object sender, EventArgs e)
        {
            if (dgvGMSBalance.RowCount > 0)
                PrintDGV.Print_DataGridView(dgvGMSBalance);
        }

    }
}
